﻿using AutoMapper;
using MediatR;
using ProcurementManagement.Applcation.Command.VendorCommand;
using ProcurementManagement.Domain.ProcurementDomain;
using ProcurementManagement.Infrstructre.Interface;

namespace ProcurementManagement.Applcation.CommandHanlers.VendorCommandHanlers
{
    public class VendorCreateCommandHanlers : IRequestHandler<VendorCreateCommand, int>
    {
        protected readonly InterfaceVendorRepository repository;
        protected readonly IMapper mapper;
        public VendorCreateCommandHanlers(InterfaceVendorRepository repository, IMapper mapper)
        {
            this.repository = repository;
            this.mapper = mapper;
        }
        public async Task<int> Handle(VendorCreateCommand request, CancellationToken cancellationToken)
        {
            // 检查供应商是否存在
            var newAdds = (await repository.GetAll()).Where(x => x.VName == request.AddDtos.VName).ToList();
            // 如果供应商存在，则返回-1
            if (newAdds.Count > 0)
            {
                return -1;
            }
            else
            {
                // 否则，添加供应商
                return await repository.AddAsync(mapper.Map<Vendor>(request.AddDtos));
            }

        }
    }
}
